/**
 * 
 */
package br.com.rodolfo.timesheet.controller;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.persistence.NoResultException;

import br.com.rodolfo.timesheet.entity.Login;
import br.com.rodolfo.timesheet.service.LoginService;

/**
 * @author rodolfo
 * 
 */
@ManagedBean(name = "loginController")
@ViewScoped
public class LoginController extends BaseController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3111400311052891953L;

	@ManagedProperty("#{loginService}")
	private LoginService loginService;

	private Login usuario;
	private String login = null, pwd = null;

	public boolean validarLogin() throws Exception {
		Login bean = new Login();
		bean.setLogin(this.getLogin());
		bean.setPwd(this.getPwd());
		usuario = loginService.logar(bean);
		return (usuario != null);

	}

	public String efetuarLogin() {
		try {
			if (validarLogin()) {
				FacesContext contexto = FacesContext.getCurrentInstance();
				contexto.getExternalContext().getSessionMap().put("usuario", usuario.getPessoa());
				System.out.println(usuario.getPessoa().getNome());
				return "principal";

			} else {
				addErrorMessage("Usuário não cadastrado.");
			}
		} catch (NoResultException ex) {
			ex.printStackTrace();
			addErrorMessage("Usuário não cadastrado.");
		} catch (Exception ex) {
			ex.printStackTrace();
			addErrorMessage("Erro: " + ex.getMessage());
		}
		return null;
	}

	public Login getUsuario() {
		return usuario;
	}

	public void setUsuario(Login usuario) {
		this.usuario = usuario;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public LoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}
}
